package com.blog.controller.admin;

import com.blog.entity.Blog;
import com.blog.entity.Blogger;
import com.blog.entity.Comment;
import com.blog.service.BlogService;
import com.blog.service.CommentService;
import com.blog.util.Const;
import com.blog.util.ResponseUtil;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


//前端用户提交评论
@Controller
@RequestMapping("/comment")
public class CommentController {
    @Resource
    private CommentService commentService;
    @Resource
    private BlogService blogService;

    @RequestMapping("/save")
    public String save(Comment comment, @RequestParam("imageCode") String imageCode, HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception {

        //获取当前登陆用户
        Blogger blogger = (Blogger) SecurityUtils.getSubject().getSession().getAttribute(Const.CURRENT_USER);

        String sRand = (String) session.getAttribute("sRand");

        JSONObject result = new JSONObject();

        int resultTotal = 0;

        if (!imageCode.equals(sRand)) {
            result.put("success", false);
            result.put("errorInfo", "验证码填写错误！");
        } else {
            comment.setUserNumber(blogger.getUserNumber());//设置评论人的学号
            comment.setUserName(blogger.getUserName());//设置评论人的姓名

            if (comment.getId() == null) {
                resultTotal = commentService.add(comment);
                Blog blog = blogService.findById(comment.getBlog().getId());
                blog.setReplyHit(blog.getReplyHit()+ 1);//评论数+1
                blogService.update(blog);
            }

            if (resultTotal > 0) {
                result.put("success", true);
            } else {
                result.put("success", false);
            }
        }

        ResponseUtil.write(response, result);

        return null;
    }
}